<?php

class DCfGocAnh extends DActiveRecord {

    private $curPage = 0;
    private $defaultSort;
    public $params;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function init() {
        parent::init();
        
        //set params
        $this->params = Yii::app()->params['goc_anh'];
    }

    public function tableName() {
        return 'cf_gocanh';
    }

    public function rules() {
        return array(
            array('title, type_id, images', 'required'),
            array('activated_flag', 'boolean'),
            array('title, images', 'length', 'max' => 255),
            array('id, folder_id, description, sort_order', 'safe'),
            array('title, type_id, activated_flag', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'rtype' => array(self::BELONGS_TO, 'NewsletterType', 'type_id'),
        );
    }

    public function attributeLabels() {
        return array(
            'type_id'        => 'Phân loại',
            'images'         => 'Image',
            'title'          => 'Tiêu đề',
            'description'    => 'Mô tả',
            'activated_flag' => 'Hiện',
            'sort_order'     => 'Sắp xếp',
        );
    }

    public function search() {
        //Restore state from session
        $this->restoreState();

        //Criteria
        $criteria       = new CDbCriteria;
        $this->setTableAlias('t');
        $criteria->with = array('rtype');

        $criteria->compare('type_id', $this->type_id);
        $criteria->compare('t.title', $this->title, true);
        $criteria->compare('t.activated_flag', $this->activated_flag);
        $criteria->compare('rtype.activated_flag', true);

        //Sorting
        $sort = new CSort();
        $sort->defaultOrder = ($this->defaultSort == '') ? array('sort_order' => true) : $this->defaultSort;
        $sort->attributes = array(
            'title' => array(
                'asc'     => 't.title ASC',
                'desc'    => 't.title DESC',
                'default' => 'asc',
            ),
            'type_id' => array(
                'asc'      => 'rtype.title ASC, t.sort_order DESC',
                'desc'     => 'rtype.title DESC, t.sort_order DESC',
                'default'  => 'asc',
            ),
            'activated_flag' => array(
                'asc'     => 't.activated_flag ASC, t.sort_order DESC',
                'desc'    => 't.activated_flag DESC, t.sort_order DESC',
                'default' => 'asc',
            ),
            'sort_order' => array(
                'asc'  => 't.sort_order ASC',
                'desc' => 't.sort_order DESC',
            ),
        );
        $sort->applyOrder($criteria);

        return new CActiveDataProvider($this, array(
            'criteria'   => $criteria,
            'sort'       => $sort,
            'pagination' => array('currentPage' => $this->curPage),
        ));
    }

    private function restoreState() {
        $state = SpsState::getState();

        if ($state) {
            if (isset($state['sort']))
                $this->defaultSort = $state['sort'];
            if (isset($state['page']))
                $this->curPage     = $state['page'];

            if (isset($state['search'])) {
                foreach ($state['search'] as $key => $value)
                    if ($value != '')
                        $this->$key = $value;
            }
        }
    }

    /**
     * Before save
     */
    protected function beforeSave() {
        parent::beforeSave();
        $this->setDefaultValue();

        return true;
    }

    protected function beforeDelete() {
        parent::beforeDelete();

        if (! empty($this->folder_id)) {
            $this->deleteFolderID($this->folder_id);
        }

        return true;
    }

    /**
     * Update user/time Sets
     */
    private function setDefaultValue() {
        if ( $this->getIsNewRecord() ) {
            $this->setAttribute('sort_order', $this->getAutoIncrement($this->tableName()));
        }

        //title_seo
        $this->setAttribute('title_seo', $this->getTitleSeo());
        
        //images
        $attr = 'images';
        if ( ! empty($this->$attr) ) {
            $pos = strrpos($this->$attr, '/');
            if ( $pos ) {
                $sTempo = substr($this->$attr, $pos + 1);
                $this->setAttribute($attr, $sTempo);
            }
        }

        return true;
    }

    private function getTitleSeo($title = '') {
        if (empty($title))
            $title = $this->title;

        $myhelpers = new MyHelpers();
        return $myhelpers->convertSeoStr($title);
    }

    private function deleteFolderID($foderID) {
        $dir = $this->params['upload_dir'] . $foderID;

        if ( is_dir($dir) ) {
            MyHelpers::getInstance()->deleteFolder($dir);
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * ========================== SORT HELPER ==========================
     */
    /**
     * Hoán đổi thuộc tính sort_order của 2 record có ID tương ứng
     * @param integer $pk1
     * @param integer $pk2 
     */
    public function swapSortOrder($pk1, $pk2) {
        $record_1    = $this->findByPk($pk1);
        $sortOrder_1 = $record_1->getAttribute('sort_order');

        $record_2    = $this->findByPk($pk2);
        $sortOrder_2 = $record_2->getAttribute('sort_order');

        //update
        $record_1->sort_order = $sortOrder_2;
        $record_1->save();

        $record_2->sort_order = $sortOrder_1;
        $record_2->save();
    }

    /**
     * Lấy Record của trang liền sau
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetLesser($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage + 1) * $pageSize;
        $command->limit(1, $offset);
        $row    = $command->queryScalar($criteria->params);

        return $row;
    }

    /**
     * Lấy Record của trang liền trước
     * @param CDBCriteria $criteria
     * @param integer $pageSize
     * @param integer $curPage
     * @return integer 
     */
    public function sortGetGreater($criteria, $pageSize, $curPage) {
        $command = Yii::app()->db->createCommand();
        $this->sortFillCommand($criteria, $command);

        //offset & limit
        $offset = ($curPage - 1) * $pageSize + ($pageSize - 1);
        $command->limit(1, $offset);

        $row = $command->queryRow(true, $criteria->params);

        return $row['id'];
    }

    /**
     * Đưa record có $pk1 lên đầu (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeTop($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order ASC'
            ));
        $criteria->compare('sort_order', '>=' . $record1->sort_order);
        $criteria->compare('sort_order', '<=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Đưa record có $pk1 xuống dưới cùng (trong trang hiện hành)
     * @param integer $pk1
     * @param integer $pk2
     */
    public function sortMakeBottom($pk1, $pk2) {
        //get records
        $record1 = $this->findByPk($pk1);
        $record2 = $this->findByPk($pk2);

        //Criteria
        $criteria = new CDbCriteria(array(
                'order' => 'sort_order DESC'
            ));
        $criteria->compare('sort_order', '<=' . $record1->sort_order);
        $criteria->compare('sort_order', '>=' . $record2->sort_order);

        $resultDB     = $this->findAll($criteria);
        $updatedValue = $record2->sort_order;

        foreach ($resultDB as $row) {
            $temp = $row->sort_order;

            $row->sort_order = $updatedValue;
            $row->save();

            $updatedValue = $temp;
        }

        return TRUE;
    }

    /**
     * Get data from $criteria into $command
     * @param type $criteria
     * @param type $command 
     */
    private function sortFillCommand($criteria, $command) {
        $command->select('T.id AS id')->from("$this->tableName() T");
        $command->leftJoin(
            'newsletter_type rtype', 'rtype.id = T.type_id'
        );

        if ($criteria->condition != '')
            $command->where($criteria->condition);
        if ($criteria->order != '')
            $command->order($criteria->order);
    }
    /**
     * ========================== END OF SORT HELPER ==========================
     */
    
    public function clearSession($scenario='') {
        unset($_SESSION['elfinder']);
        unset($_SESSION['file_manager']);

        if ($scenario=='insert') {
            $this->deleteFolderID(Yii::app()->user->getState('gocanh_folder_id'));
        }
        Yii::app()->user->setState('gocanh_folder_id', null);
    }
}